﻿using CnBlogsClient.Global;
using CnBlogsClient.Interface;
using CnBlogsClient.ViewModels;
using CnBlogsCore.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Xamarin.Forms;
using Xamarin.Forms.PlatformConfiguration;
using Xamarin.Forms.Xaml;

namespace CnBlogsClient.Views.Articles
{
    [XamlCompilation(XamlCompilationOptions.Compile)]
    public partial class KbArticlePage : ContentPage
    {
        KbArticleViewModel ViewModel => vm ?? (vm = BindingContext as KbArticleViewModel);
        KbArticleViewModel vm;

        bool hasInitialization;

        public KbArticlePage()
        { 
            InitializeComponent();
            Icon = "menu_kbarticles.png";
            Xamarin.Forms.NavigationPage.SetHasNavigationBar(this, false);
        }

        protected override void OnAppearing()
        {
            base.OnAppearing();

            if (!hasInitialization)
            {
                BindingContext = new KbArticleViewModel();

                Title = "知识库";

                this.kbArticleListView.ItemSelected += async delegate {
                    var kbArticles = kbArticleListView.SelectedItem as KbArticle;
                    this.kbArticleListView.SelectedItem = null;

                    if (kbArticles == null)
                        return;

                    var detailPage = new KbArticleDetailsPage(kbArticles);
                    await NavigationService.PushAsync(Navigation, detailPage);
                };

                hasInitialization = true;
            }

            UpdatePage();
        }

        private void UpdatePage()
        {
            bool forceRefresh = (DateTime.Now > (ViewModel?.NextRefreshTime ?? DateTime.Now));
            if (forceRefresh)
            {
                ViewModel.RefreshCommand.Execute(null);
            }
        }
    }
}